﻿using System;
using System.Collections.Generic;
using System.IO;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Framework.Serialization;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.Logic;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public static class StoryActionGlobal
    {
        private static Dictionary<int, StoryActionConfig> _actionDict = new();

#if UNITY_EDITOR
        public static Dictionary<int, StoryActionConfig> actionDict
        {
            get
            {
                if (_actionDict.Count <= 0)
                {
                    Load();
                }
                return _actionDict;
            }
        }
#endif

        public static StoryActionConfig Get(int actionID)
        {
            if (_actionDict.TryGetValue(actionID, out var rConfig))
            {
                return rConfig;
            }
            Load();
            return _actionDict.TryGetValue(actionID, out rConfig) ? rConfig : null;
        }

        public static void Clear()
        {
            _actionDict.Clear();
        }

        private static void Load()
        {
            // load
            byte[] bytes;
            var rLoader = ResLoader.Create();
#if UNITY_EDITOR
            if (StoryClientUtil.IsEditorMode)
            {
                var rPath = "Assets/" + PathConstant.StoryActionCfgPath;
                if (File.Exists(rPath))
                {
                    bytes = File.ReadAllBytes(rPath);
                }
                else
                {
                    bytes = Array.Empty<byte>();
                }
            }
            else
#endif
            {
                var rFile = rLoader.LoadABAsset<TextAsset>(PathConstant.StoryActionCfgPath);
                if (rFile != null)
                {
                    bytes = rFile.bytes;
                }
                else
                {
                    bytes = Array.Empty<byte>();
                }
            }
            if (bytes.Length > 0)
            {
                var rByteBuf = ThreadLocalTemporalByteBufPool.Alloc(bytes.Length);
                rByteBuf.Replace(bytes);
                var rList = rByteBuf.DeSerializeList<StoryActionConfig>();
                ThreadLocalTemporalByteBufPool.Free(rByteBuf);
                for (int i = 0; i < rList.Count; i++)
                {
                    _actionDict.TryAdd(rList[i].id, rList[i]);
                }
            }
            rLoader?.Put2Pool();
        }
    }
}